<template>
	<s-layout :title="state.title" :bgStyle="{ color: '#f2f2f2' }">

		<su-sticky bgColor="#fff">
			<view class="item">
				<image :src="sheep.$url.static(state.brand.logo)" class="banner"/>
				<view class="bottom">
					<view class="left">
						<text class="title">专题：{{ state.brand.name }}</text>
					</view>
				</view>
			</view>
		</su-sticky>

    <view v-if="state.pagination.total > 0" class="goods-list ss-m-t-20">
      <view
        class="ss-p-l-20 ss-p-r-20 ss-m-b-20"
        v-for="item in state.pagination.data"
        :key="item.id"
      >
        <s-goods-column
          class=""
					:tag-style="tagStyle"
          size="lg"
          :data="item"
          :topRadius="10"
          :price-unit="'元'"
          :bottomRadius="10"
          @click="sheep.$router.go('/pages/goods/preIndex', { id: item.id })"
        >
	        <template v-slot:cart>
		        <button class="ss-reset-button cart-btn" :style="[buyStyle]">
			        {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
		        </button>
	        </template>
        </s-goods-column>
      </view>
    </view>
    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-empty v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" text="暂无商品">
    </s-empty>
  </s-layout>
</template>

<script setup>
import {computed, reactive} from 'vue';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import _ from 'lodash';

  const sys_navBar = sheep.$platform.navbar;
  const emits = defineEmits(['close', 'change']);

	const tagStyle = {
		show: 1,
		src: ""
	}

  const pagination = {
    data: [],
    current_page: 1,
    total: 1,
    last_page: 1,
    size: 6
  };

  const buyNowStyle = {
	  "mode": 0,
			  "text": "立即下单",
			  "color1": "#e16759",
			  "color2": "#f5796f",
			  "src": "\/storage\/decorate\/20221115\/4782356b4587dc4f4a218f2540a0bafc.png",
			  "right": '20rpx',
			  "bottom":"18rpx"
  };

  // 下单按钮样式
  const buyStyle = computed(() => {
	  if (buyNowStyle.mode === 1) {
		  // button
		  return {
			  background: `linear-gradient(to right, ${buyNowStyle.color1}, ${buyNowStyle.color2})`,
		  };
	  }

	  if (buyNowStyle.mode === 2) {
		  // image
		  return {
			  width: '54rpx',
			  height: '54rpx',
			  background: `url(${sheep.$url.cdn(buyNowStyle.src)}) no-repeat`,
			  backgroundSize: '100% 100%',
		  };
	  }
  });

  const state = reactive({
    pagination: {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
      size: 10
    },
	  brand: {},
    currentSort: 'sort',
    currentOrder: 'desc',
    currentTab: 0,
    filterParams: {},
    curFilter: 0,
    showFilter: false,
    iconStatus: true,
    tabList: [
      {
        name: '综合推荐',
        value: 'sort',
        order: 'asc',
        list: [
          {
            label: '综合推荐',
            sort: 'sort',
            order: 'desc',
          },
          /*{
            label: '价格升序',
            sort: 'price',
            order: 'asc',
          },
          {
            label: '价格降序',
            sort: 'price',
            order: 'desc',
          },*/
        ],
      },
        //没有销量字段，暂时隐藏
      // {
      //   name: '销量',
      //   value: 'total_sales',
      // },
      {
        name: '商品状态',
        value: 'status',
        order: 'desc',
        list: [
					{
						label: '全部',
						status: '',
						sort: 'status',
            order: 'desc',
					},
					{
						label: '非SOLD',
						status: 'on_sale',
						sort: 'status',
            order: 'desc',
					},
					{
						label: '已SOLD',
						status: 'sold_out',
						sort: 'status',
            order: 'desc',
					},
				],
      },
	    {
		    name: '价格筛选',
		    value: 'price',
		    order: 'desc',
		    list: [
			    {
				    label: '价格筛选',
				    sort: 'price',
				    order: 'desc',
			    },
			    {
				    label: '查询',
				    sort: 'priceSearch',
				    order: 'desc',
			    },
		    ],
	    },
    ],
    loadStatus: '',
    keyword: '',
    platform: null,
	  status: '',
	  price_min: null,
	  price_max: null,
    leftGoodsList: [],
    rightGoodsList: [],
	  categoryId: '',
	  categoryName: '全部商品',
	  bannerList: [],
	  platformImg: [],
	  noticeInfo: {},
	  versionInfo: {},
	  currentCategoryTab: 0,
	  goodCategory: [
		  {
			  id: 1328,
			  name: '精选好物',
			  child: [
				  {
					  id: '1328',
					  name: '全部商品'
				  }
			  ]
		  }
	  ],
	  tabMapsStorage: [
		  {
			  name: '全部商品',
			  value: -1,
			  categoryId: 1328
		  }
	  ]
  });

  // 加载瀑布流
  let count = 0;
  let leftHeight = 0;
  let rightHeight = 0;

  function mountMasonry(height = 0, where = 'left') {
    if (!state.pagination.data[count]) return;
    if (count %2 === 0) {
      state.leftGoodsList.push(state.pagination.data[count]);
    } else {
      state.rightGoodsList.push(state.pagination.data[count]);
    }
    // if (!state.pagination.data[count]) return;
    //
    // if (where === 'left') {
    //   leftHeight += height;
    // } else {
    //   rightHeight += height;
    // }
    // if (leftHeight <= rightHeight) {
    //   state.leftGoodsList.push(state.pagination.data[count]);
    // } else {
    //   state.rightGoodsList.push(state.pagination.data[count]);
    // }
    count++;
  }

  function emptyList() {
    state.pagination = {...pagination}
    state.leftGoodsList = [];
    state.rightGoodsList = [];
    count = 0;
    leftHeight = 0;
    rightHeight = 0;
  }

function onTabsChangeStorage(e) {
	console.log('onTabsChangeStorage', e)
	state.categoryId = e.categoryId;
	state.categoryName = e.name;
	emptyList();
	getList();
}

  //搜索
  function onSearch(e) {
    state.keyword = e;
    emptyList();
    getList();
  }

  // 点击
  function onTabsChange(e) {
    if (state.tabList[e.index].list) {
      state.currentTab = e.index;
      state.showFilter = !state.showFilter;
      return;
    } else {
      state.showFilter = false;
    }
    if (e.index === state.currentTab) {
      return;
    } else {
      state.currentTab = e.index;
    }
    emptyList();
    state.currentSort = e.value
    state.currentOrder = e.order
    getList();
  }

  // 点击筛选项
  const onFilterItem = (val) => {
	  console.log(val)
		if (val.sort === 'status') {
			state.status = val.status
		}
		if (val.sort === 'price') {
			return
		}
		/*if (val.sort === 'priceSearch') {
			if (!(state.price_min > 0 && state.price_min <= state.price_max)) {
				sheep.$helper.toast('请输入正确的价格区间')
			}
		}*/
    emptyList();
    getList();
    state.showFilter = false;
  };

	function onPriceChangeMin() {
		if (state.price_min < 0 || state.price_max < 0) {
			sheep.$helper.toast('请输入正确的价格区间')
			state.price_min = 0
			state.price_max = 10000
		}
		if (state.price_min <= state.price_max) {
			sheep.$helper.toast('请输入正确的价格区间')
			state.price_min = 0
			state.price_max = 10000
		}
	}
	function onPriceChangeMax() {
		if (state.price_min < 0 || state.price_max < 0) {
			sheep.$helper.toast('请输入正确的价格区间')
			state.price_min = null
			state.price_max = null
		}
		if (state.price_min <= state.price_max) {
			sheep.$helper.toast('请输入正确的价格区间')
			state.price_min = null
			state.price_max = null
		}
	}

  async function getList() {
		// 提示商品加载中
	  sheep.$helper.toast('商品拼命加载中...')
    state.loadStatus = 'loading';
    const params = {
      search:state.keyword,
      categoryId: state.categoryId,
      brandId: state.brand.id,
      orderField: state.currentSort,
      orderSort: state.currentOrder,
	    status: state.status,
	    price_min: state.price_min,
	    price_max: state.price_max,
	    platform: state.platform,
    }
	  console.log(params)
    const res = await sheep.$api.goods.listPre(params, { page:state.pagination.current_page - 1, size: state.pagination.size });
    const { content, totalElements, totalPages } = res;
		if (content.length === 0) {
			state.loadStatus = 'noMore';
			return;
		}
    state.pagination.data = _.concat(state.pagination.data, content)
    state.pagination.total = totalElements
    mountMasonry();
	  state.loadStatus = 'more';
  }
  // 加载更多
  function loadmore() {
    if (state.loadStatus !== 'noMore') {
      state.pagination.current_page++;
      getList();
    }
  }
  onLoad((options) => {
	  // 请求推荐分类信息
	  /*sheep.$api.category.list({
		  parentId: 1328
	  }).then(category => {
		  category.forEach((item,index) => {
			  let obj = {
				  name: item.name,
				  value: index,
				  categoryId: item.id
			  }
			  state.tabMapsStorage.push(obj)
		  })
		  console.log(state.tabMapsStorage, 'state.tabMapsStorage')
	  })*/
    state.keyword = options.keyword;
    state.platform = options.platform;
		if ( !sheep.$helper.isRealEmpty(options.categoryName)){
			state.categoryName = options.categoryName;
		}
	  if ( !sheep.$helper.isRealEmpty(options.categoryId)){
		  state.categoryId = options.categoryId;
	  }
		state.brand.id = options.brandId;
		state.brand.name = options.brandName;
		state.brand.logo = options.brandLogo;
    getList();
  });
  // 上拉加载更多
  onReachBottom(() => {
    loadmore();
  });
</script>

<style lang="scss" scoped>
  .goods-list-box {
    width: 50%;
    box-sizing: border-box;
    .left-list {
      margin-right: 10rpx;
      margin-bottom: 20rpx;
    }
    .right-list {
      margin-left: 10rpx;
      margin-bottom: 20rpx;
    }
  }
  .goods-box {
    &:nth-last-of-type(1) {
      margin-bottom: 0 !important;
    }
    &:nth-child(2n) {
      margin-right: 0;
    }
  }
  .list-icon {
    width: 80rpx;
    .sicon-goods-card {
      font-size: 40rpx;
    }
    .sicon-goods-list {
      font-size: 40rpx;
    }
  }
  .goods-card {
    margin-left: 20rpx;
  }
  .list-filter-tabs {
    background-color: #fff;
  }
  .filter-list-box {
    padding: 28rpx 52rpx;
    .filter-item {
      font-size: 28rpx;
      font-weight: 500;
      color: #333333;
      line-height: normal;
      margin-bottom: 24rpx;
      &:nth-last-child(1) {
        margin-bottom: 0;
      }
    }
    .filter-item-active {
      color: var(--ui-BG-Main);
    }
  }
  .tab-item {
    height: 50px;
    position: relative;
    z-index: 11;

    .tab-title {
      font-size: 30rpx;
    }

    .cur-tab-title {
      font-weight: $font-weight-bold;
    }

    .tab-line {
      width: 60rpx;
      height: 6rpx;
      border-radius: 6rpx;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 10rpx;
      background-color: var(--ui-BG-Main);
      z-index: 12;
    }
  }

  .cart-btn {
	  position: absolute;
	  bottom: 18rpx;
	  right: 20rpx;
	  z-index: 11;
	  height: 50rpx;
	  line-height: 50rpx;
	  padding: 0 20rpx;
	  border-radius: 25rpx;
	  font-size: 24rpx;
	  color: #fff;
  }
  .tag-bar {
	  width: 100%;
	  background-image: linear-gradient(90deg, #F48989 0%, #fad0c4 100%);
	  background-position: left center;
	  background-repeat: no-repeat;
	  background-size: cover;
	  border-radius: 10rpx 0 10rpx 0;
	  color: #ffffff;
	  font-weight: bold;
	  font-size: 30rpx;
	  padding: 5rpx;
	  text-align: center;
	  margin-bottom: 10rpx;
	  font-style: italic
  }

  .bottom {
	  display: flex;
	  justify-content: space-between;
	  padding: 10rpx;

	  .left {
		  display: flex;
		  align-items: center;
		  padding: 20rpx;
		  font-weight: 400;
		  color: #d27d7d;
	  }

	  .right {
		  display: flex;
		  align-items: center;
		  color: #d27d7d;
	  }
  }

  .item {
	  width: 95%;
	  margin-left: 2.5%;
	  border-radius: 20rpx;
	  background: #fff;
	  margin-top: 30rpx;
	  box-shadow: 1px 1px 50px #ffffff;
  }

  .banner {
	  width: 97%;
	  margin-left: 1.5%;
	  margin-top: 10rpx;
	  border-radius: 10rpx;
	  height: 260rpx;
	  box-shadow: 1px 1px 50px #cccccc
  }
</style>
